<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="goBack"><ion-icon :icon="chevronBackOutline"></ion-icon></ion-button>
        </ion-buttons>
        <ion-title text-align="center">LogsList</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="openCreateModal"><ion-icon :icon="addOutline"></ion-icon></ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <ion-card v-for="log in logs" :key="log.commentId" style="background-color: bisque;">
      <ion-grid>
        <ion-list v-if="logs.length">
            <ion-item>
            <ion-row 
              @touchstart="startLongPress($event, log.commentId)"
              @touchend="cancelLongPress"
              @mousedown="startLongPress($event, log.commentId)"
              @mouseup="cancelLongPress"
              @mouseleave="cancelLongPress"
              class="log-row"
              >
              <ion-col size="1.5">BA:</ion-col>             
              <ion-col size="3.5" @click.stop="toggleExpand(log.commentId)">{{ log.name }}</ion-col>
              <ion-col size="7" @click.stop="toggleExpand(log.commentId)" style="color: #666;font-size: 0.9em">{{ log.date }}</ion-col>
              <ion-col size="12" @click.stop="toggleExpand(log.commentId)">
                <div class="comment-preview">{{ log.comment }}</div>
              </ion-col>
            </ion-row>
          </ion-item> 
            <!-- 展开详情 -->
            <div v-show="expandedLogId === log.commentId" class="detail-panel">
              <div class="detail-content">
                <h5 style="color: black;">content: </h5>
                <h4>{{ log.comment }}</h4>
                <!-- <div class="meta-info">
                  <span>time : {{ log.date }}</span>
                </div> -->
                
                <!-- 评论区域 -->
                <!-- <div class="comments" v-if="log.comments?.length">
                  <div v-for="comment in log.comments" :key="comment.commentId" class="comment-item">
                    <p class="comment-content">{{ comment.comment }}</p>
                    <span class="comment-time">{{ comment.date}}</span>
                  </div>
                </div> -->
              </div>
            </div>
        </ion-list>
        <div v-else class="empty-state">
          No data
        </div>
      </ion-grid>
    </ion-card>
      <!-- 新建日志模态框 -->
      <ion-modal :is-open="isCreateModalOpen">
          <ion-toolbar>
            <ion-title>new logs</ion-title>
            <ion-buttons slot="end">
              <ion-button @click="closeCreateModal">close</ion-button>
            </ion-buttons>
          </ion-toolbar>
        <ion-content class="ion-padding">
          <ion-input v-model="newLog.content" placeholder="please enter..." fill="outline"></ion-input>
          <ion-button expand="block" @click="createLog" class="submit-btn">post</ion-button>
        </ion-content>
      </ion-modal>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { 
  IonPage, IonHeader, IonToolbar, IonTitle, IonContent, 
  IonGrid, IonCol, IonList, IonRow, IonButton,
  IonModal, IonInput,IonButtons,IonItem,IonIcon,IonCard

} from '@ionic/vue';
import { chevronBackOutline,addOutline } from 'ionicons/icons';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { watch } from 'vue';
import { useRoute } from 'vue-router';
import logapi from '@/api/logapi'
// import axios from 'axios';
const route = useRoute();

// 焦点管理逻辑
watch(() => route.path, (newPath) => {
  if (!newPath.includes('/logs')) { 
    // 当离开页面时移除所有焦点
    (document.activeElement as HTMLElement)?.blur();
  }
});
const goBack = () => {
  router.go(-1); 
};
interface Log {
  commentId: string;
  comment: string;
  name:string
  date: string;
  comments?: Comment[];
}

interface Comment {
  commentId: string;
  comment: string;
  date: string;
  name:string
}

const router = useRouter();
const logs = ref<Log[]>([]);
const isCreateModalOpen = ref(false);
const newLog = ref({
  content: ''
});
// 新增响应式状态
const expandedLogId = ref<string | null>(null);

// 切换展开状态
const toggleExpand = (logId: string) => {
  expandedLogId.value = expandedLogId.value === logId ? null : logId;
};
 const accessToken = localStorage.getItem('accessToken');
 const longPressTimer = ref<number | null>(null);
const longPressCommentId = ref<string | null>(null);

const startLongPress = (event: Event, commentId: string) => {
  event.preventDefault();
  longPressCommentId.value = commentId;
  longPressTimer.value = window.setTimeout(() => {
    deleteLog(commentId);
  }, 1500); // 长按触发
};

const cancelLongPress = () => {
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value);
    longPressTimer.value = null;
    if (longPressCommentId.value) {
      toggleExpand(longPressCommentId.value);
      longPressCommentId.value = null;
    }
  }
};


// 获取日志列表
const fetchLogs = async () => {
  try {
    const response = await logapi.get('/shift/handover/log/list',{
      params:{
        start:0,
        length:20
      }
    });
    logs.value = response.data.data.list;
    console.log(response.data)
  } catch (error) {
    console.error('获取日志失败:', error);
  }
};
onMounted(fetchLogs)
// 删除日志
const deleteLog = async (commentId: string) => {
  const confirm = window.confirm('User can only delete his/her message! Confirm this action?');
  if (!confirm) return;
  try {
    await logapi.post(`/shift/handover/log/delete`,
      {  
        commentId,
        userId: localStorage.getItem('userId'),
      }
    );
    await fetchLogs();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

// 新建日志
const createLog = async () => {
  try {
    const requestData = {
      comment: newLog.value.content,
      userId: localStorage.getItem('userId')
    };
    const response = await logapi.post('/shift/handover/log/add', requestData,
    {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}` 
      },
      }
    );
    console.log('创建日志响应:', response); // 调试输出
    closeCreateModal();
    await fetchLogs();
    newLog.value.content = '';
  } catch (error: any) {
     // 显示具体错误信息
     if (error.response) {
      console.log('错误状态码:', error.response.status);
      console.log('错误响应头:', error.response.headers);
      console.log('错误数据:', error.response.data);
      
      if (error.response.status === 403) {
        alert('权限不足，请联系管理员');
      } else if (error.response.status === 500) {
        alert('服务器错误：' + error.response.data.msg);
      }
    }
    
    if (error.response?.status === 401) {
      router.push('/login');
    }
  }
};


// 模态框控制
const openCreateModal = () => isCreateModalOpen.value = true;
const closeCreateModal = () => isCreateModalOpen.value = false;


onMounted(fetchLogs);
</script>

<style scoped>
.log-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.fixed-col {
  flex: 0 0 auto;
  min-width: 0; /* 允许内容截断 */
}

.name-col {
  width: 20%; /* 根据需求调整具体比例 */
  max-width: 120px;
}

.date-col {
  width: 25%;
  max-width: 150px;

}

.comment-col {
  flex: 1 1 auto;
  min-width: 0; /* 关键：允许内容溢出截断 */
  overflow: hidden;
}


.comment-col {
  flex: 1 1 auto;
  min-width: 0; /* 关键：允许内容溢出截断 */
  overflow: hidden;
}

.comment-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: block;
  padding: 8px 0;
  line-height: 1.4;
}
.content-col {
  cursor: pointer;
  &:hover {
    color: #3880ff;
    text-decoration: underline;
  }
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
}

.submit-btn {
  margin-top: 20px;
}

ion-modal {
  --width: 80%;
  --height: 50%;
}
ion-toolbar ion-title {
  padding: 0 20px;
}
.detail-panel {
  width: 100%;
  padding: 12px;
  background: #f8f9fa;
  border-top: 1px solid #eee;
  animation: slideDown 0.3s ease;
}

.detail-content {
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* .meta-info {
  margin-top: 12px;
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 0.9em;
} */

.comments {
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 12px;
}

.comment-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-content {
  margin: 0;
  color: #333;
}

.comment-time {
  font-size: 0.8em;
  color: #999;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 调整点击区域样式 */
ion-col[size="2"],
ion-col[size="4"],
ion-col[size="3"] {
  cursor: pointer;
  transition: background 0.2s;
  
  &:hover {
    background: #f5f5f5;
  }
}
</style>